package com.acme.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.transaction.Transactional;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.acme.dao.ChatDAO;
import com.acme.dao.UserDAO;
import com.acme.dao.security.DBUserDAO;
import com.acme.entity.Chat;
import com.acme.entity.User;
import com.acme.entity.security.DBUserDetails;

@Transactional
@Controller
@RequestMapping("ChatTest")
public class ChatTestController {
	
	@Autowired
	ChatDAO chatDAO;

	@Autowired
	UserDAO userDAO;

	@Autowired
	private DBUserDAO dbuserDAO;

//	private static final Logger logger = LoggerFactory.getLogger(HomeController.class);

	@RequestMapping(method=RequestMethod.GET)
	public String getMessages() {
//		logger.info("Page get");

		return "ChatTest";
	}

	@RequestMapping(method=RequestMethod.POST)
	public @ResponseBody List<Chat> postMessages(HttpServletRequest request) {
		String username = SecurityContextHolder.getContext().getAuthentication().getName();

		String oldTime = request.getParameter("oldTime");
		String currentTime = request.getParameter("currentTime");
		List<Chat> chatLog = chatDAO.getAllChat();
		
		if(request.getParameter("command").equals("post")){
			String message = request.getParameter("message");
			
			Chat chat = new Chat();
			chat.setuName(username);
			chat.setMessage(message);
			chat.setTime(currentTime);
			
			chatDAO.updateChat(chat, "100000");
			chatLog = chatDAO.getAllChatAfterTime(oldTime);
			
//			for (Chat c : chatLog) {
//				logger.info("Message inside of post: " + c.getuName() + ": " + c.getMessage() + "; Time: " + c.getTime());
//			}
		}
		
		if(request.getParameter("command").equals("sync")){
			chatLog = chatDAO.getAllChatAfterTime(oldTime);
//			logger.info("Chat refreshed. Old time is " + oldTime);
//			if(!chatLog.isEmpty()){
//				logger.info("someone retrieved a message");
//			}
		}

		
//		for (Chat chat : chatLog) {
//			logger.info(chat.getuName() + ": " + chat.getMessage());
//		}
		
		return chatLog;

	}

}